package com.sunny.l27;

public class Solution {

    private int maxPath = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return maxPath;
    }

    public int dfs(TreeNode node){
        if(null == node){
            return 0;
        }
        int left = dfs(node.left);
        int right = dfs(node.right);
        int tmpMax;
        if(left <= 0 && right <= 0)
            tmpMax = node.val;
        else if(left <= 0)
            tmpMax = node.val + right;
        else if(right <= 0)
            tmpMax = node.val + left;
        else
            tmpMax = node.val + left + right;
        if(tmpMax > maxPath)
            maxPath = tmpMax;

        int retMax = Integer.max(left, right);
        retMax = retMax<0?0:retMax;
        return retMax + node.val;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
